package dshop.model.permission;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.jfinal.plugin.activerecord.Record;

import appbase.jfinal.ext.BaseModel;
import appbase.jfinal.ext.ModelKit;

public class PermissionUser extends BaseModel<PermissionUser>{
	
	private static final long serialVersionUID = -6967680902549117464L;
	
	public static final PermissionUser dao = new PermissionUser();

	public static void save(int userId, List<Integer> permIds) 
	{
		delete(userId);
		
		if (permIds == null || permIds.isEmpty()) 
		{
			return;
		}
		
		List<PermissionUser> perms = new ArrayList<PermissionUser>();
		for (int permId : permIds)
		{
			PermissionUser perm = new PermissionUser();
			perm.set("userId", userId)
				.set("permId", permId);
			perms.add(perm);
		}
		dao.saveList(perms);
	}

	public static void delete(int userId) 
	{
		dao.deleteByColumns("userId", userId);
	}

	/**
	 * @return [{.., hasPerm}]
	 */
	public static void setStatusTo(List<Record> list, String permIdColumn, int userId) 
	{
		dao.mergeStatusColumnTo(list, permIdColumn, "permId", "hasPerm", "userId", userId);
	}

	public static Set<String> getPermSet(int userId) 
	{
		String sql = "select d.perm from permission_user u inner join permission_dict d on d.id = u.permId where u.userId = ?";
		List<PermissionUser> perms = dao.find(sql, userId);
		Set<String> permSet = new HashSet<String>();
		for (PermissionUser perm : perms) 
		{
			String permStr = perm.getStr("perm");
			if (permStr != null && !permStr.isEmpty()) 
			{
				permSet.add(permStr);
			}
		}
		return permSet;
	}

	
	public static List<String> listOf(int userId) 
	{
		String sql = " select p.perm " 
				   + " from permission_user pu "
				   + " inner join permission_dict p on p.id = pu.permId "
				   + " where pu.userId = ? ";
		List<PermissionUser> list = dao.find(sql, userId);
		return ModelKit.getToList(list, "perm", String.class);
	}
	
}
